package com.clear.club.circle.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clear.club.circle.api.common.PageInfo;
import com.clear.club.circle.api.common.PageResult;
import com.clear.club.circle.api.enums.IsDeletedFlagEnum;
import com.clear.club.circle.api.req.GetMomentsReq;
import com.clear.club.circle.api.req.RemoveMomentCircleReq;
import com.clear.club.circle.api.req.SaveMomentCircleReq;
import com.clear.club.circle.api.vo.ShareMomentVO;
import com.clear.club.circle.server.entity.po.ShareMoment;
import com.clear.club.circle.server.dao.ShareMomentMapper;
import com.clear.club.circle.server.service.IShareMomentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 动态信息 服务实现类
 * </p>
 *
 * @author 宁洪康
 * @since 2024-07-03
 */
@Service
public class ShareMomentServiceImpl extends ServiceImpl<ShareMomentMapper, ShareMoment> implements IShareMomentService {

    /**
     * 发布内容
     */
    @Override
    public Boolean saveMoment(SaveMomentCircleReq req) {
        ShareMoment shareMoment = new ShareMoment();
        shareMoment.setCircleId(req.getCircleId());
        shareMoment.setContent(req.getContent());
        if (!CollectionUtils.isEmpty(req.getPicUrlList())) {
            shareMoment.setPicUrls(JSON.toJSONString(req.getPicUrlList()));
        }
        shareMoment.setReplyCount(0);
        // todo 暂时写死
        shareMoment.setCreatedBy("小黑子卤出鸡脚");
        shareMoment.setCreatedTime(LocalDateTime.now());
        shareMoment.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());

        return this.save(shareMoment);
    }

    /**
     * 删除动态内容
     */
    @Override
    public Boolean removeMoment(RemoveMomentCircleReq req) {
        LambdaUpdateWrapper<ShareMoment> updateWrapper = Wrappers.<ShareMoment>lambdaUpdate()
                .eq(ShareMoment::getId, req.getId())
                .eq(ShareMoment::getIsDeleted, IsDeletedFlagEnum.UN_DELETED.getCode())
                .set(ShareMoment::getIsDeleted, IsDeletedFlagEnum.DELETED.getCode());
        return this.update(updateWrapper);
    }

    /**
     * 分页查询动态内容
     */
    @Override
    public PageResult<ShareMomentVO> getMoments(GetMomentsReq req) {
        // 例如：select * from share_moment where is_deleted = 0 and circle_id = 2 order by circle_id desc;
        LambdaQueryWrapper<ShareMoment> queryWrapper = Wrappers.<ShareMoment>lambdaQuery()
                .eq(ShareMoment::getIsDeleted, IsDeletedFlagEnum.UN_DELETED.getCode())
                .eq(ShareMoment::getCircleId, req.getCircleId())
                .orderByDesc(ShareMoment::getCircleId);
        PageInfo pageInfo = req.getPageInfo();

        // 1.分页查询，new Page()的两个参数分别是：页码、每页大小
        Page<ShareMoment> page = new Page<>(pageInfo.getPageNo(), pageInfo.getPageSize());
        Page<ShareMoment> pageRes = this.page(page,queryWrapper);   // page == pageRes
        // 组装查询结果
        PageResult<ShareMomentVO> result = new PageResult<>();
        List<ShareMoment> records = pageRes.getRecords();
        List<ShareMomentVO> collect = records.stream().map(item -> {
            ShareMomentVO vo = new ShareMomentVO();
            vo.setId(item.getId());
            vo.setCircleId(item.getCircleId());
            vo.setContent(item.getContent());
            if (Objects.nonNull(item.getPicUrls())) {
                List<String> picList = JSONArray.parseArray(item.getPicUrls(), String.class);
                vo.setPicUrlList(picList);
            }
            vo.setReplyCount(item.getReplyCount());
            vo.setCreatedTime(item.getCreatedTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());

            return vo;
        }).collect(Collectors.toList());
        result.setRecords(collect);
        result.setTotal((int) pageRes.getTotal());
        result.setPageNo(pageInfo.getPageNo());
        result.setPageSize(pageInfo.getPageSize());

        return result;
    }
}
